<template>
  <div class="dynamic-menu" :class="{ collapsed: isCollapsed }">
    <!-- 菜单头部 -->
    <div class="menu-header">
      <div class="menu-title" v-show="!isCollapsed">
        <span class="title-text">导航菜单</span>
      </div>
      <el-button
        class="collapse-btn"
        type="text"
        @click="toggleCollapse"
        :title="isCollapsed ? '展开菜单' : '折叠菜单'"
      >
        <el-icon>
          <component :is="isCollapsed ? 'Expand' : 'Fold'" />
        </el-icon>
      </el-button>
    </div>

    <!-- 菜单内容 -->
    <div class="menu-content">
      <el-menu
        :default-active="activeMenu"
        :collapse="isCollapsed"
        :unique-opened="true"
        @select="handleMenuSelect"
        class="menu-list"
      >
        <template v-for="menu in filteredMenus" :key="menu.key">
          <!-- 有子菜单的情况 -->
          <el-sub-menu
            v-if="menu.children && menu.children.length > 0"
            :index="menu.key"
            :disabled="!hasMenuPermission(menu)"
          >
            <template #title>
              <el-icon class="menu-icon">
                <span v-if="menu.icon" class="emoji-icon">{{ menu.icon }}</span>
                <component v-else :is="getDefaultIcon(menu.key)" />
              </el-icon>
              <span class="menu-label">{{ menu.label }}</span>
            </template>
            
            <el-menu-item
              v-for="child in menu.children"
              :key="child.key"
              :index="child.key"
              :disabled="!hasMenuPermission(child)"
              @click="handleMenuClick(child)"
            >
              <el-icon class="menu-icon">
                <span v-if="child.icon" class="emoji-icon">{{ child.icon }}</span>
                <component v-else :is="getDefaultIcon(child.key)" />
              </el-icon>
              <span class="menu-label">{{ child.label }}</span>
            </el-menu-item>
          </el-sub-menu>

          <!-- 没有子菜单的情况 -->
          <el-menu-item
            v-else
            :index="menu.key"
            :disabled="!hasMenuPermission(menu)"
            @click="handleMenuClick(menu)"
          >
            <el-icon class="menu-icon">
              <span v-if="menu.icon" class="emoji-icon">{{ menu.icon }}</span>
              <component v-else :is="getDefaultIcon(menu.key)" />
            </el-icon>
            <span class="menu-label">{{ menu.label }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="menu-loading">
      <el-skeleton :rows="6" animated />
    </div>

    <!-- 空状态 -->
    <div v-else-if="filteredMenus.length === 0" class="menu-empty">
      <el-empty description="暂无可用菜单" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useMenuStore } from '@/stores/menuStore'
import { useUserAuthStore } from '@/stores/userAuth'
import {
  House,
  ChatDotRound,
  Folder,
  User,
  Document,
  Setting,
  Phone,
  Expand,
  Fold,
  Menu,
  DocumentCopy,
  Calendar,
  Users,
  ScaleToOriginal,
  OfficeBuilding,
  Tools,
  Lock,
  UserFilled
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const menuStore = useMenuStore()
const userAuthStore = useUserAuthStore()

// 响应式数据
const loading = computed(() => menuStore.loading)
const filteredMenus = computed(() => menuStore.filteredMenus)
const activeMenu = computed(() => menuStore.activeMenu)
const isCollapsed = computed(() => menuStore.isCollapsed)

// 图标映射
const iconMap = {
  home: House,
  consultation: ChatDotRound,
  'case-management': Folder,
  'case-list': DocumentCopy,
  'case-create': Document,
  'case-analysis': Document,
  'lawyer-services': User,
  'lawyer-team': Users,
  'lawyer-center': ScaleToOriginal,
  appointment: Calendar,
  resources: Document,
  'legal-resource': Document,
  'legal-news': Document,
  'legal-templates': DocumentCopy,
  system: Setting,
  'user-management': UserFilled,
  'role-management': Lock,
  'system-settings': Tools,
  contact: Phone
}

// 获取默认图标
const getDefaultIcon = (key) => {
  return iconMap[key] || Menu
}

// 检查菜单权限
const hasMenuPermission = (menu) => {
  const userType = userAuthStore.userType
  const permissions = userAuthStore.permissions
  
  // 检查角色权限
  if (menu.roles && !menu.roles.includes(userType)) {
    return false
  }
  
  // 检查具体权限
  if (menu.permission && !permissions.includes(menu.permission)) {
    return false
  }
  
  // 检查多个权限（任一满足即可）
  if (menu.permissions && !menu.permissions.some(p => permissions.includes(p))) {
    return false
  }
  
  return true
}

// 处理菜单选择
const handleMenuSelect = (key) => {
  menuStore.setActiveMenu(key)
}

// 处理菜单点击
const handleMenuClick = (menu) => {
  if (menu.path) {
    router.push(menu.path)
  }
  menuStore.setActiveMenu(menu.key)
}

// 切换折叠状态
const toggleCollapse = () => {
  menuStore.toggleCollapsed()
}

// 根据当前路由设置激活菜单
const setActiveMenuByRoute = () => {
  const currentPath = route.path
  const menu = menuStore.findMenuByPath(currentPath)
  if (menu) {
    menuStore.setActiveMenu(menu.key)
  }
}

// 监听路由变化
watch(() => route.path, () => {
  setActiveMenuByRoute()
})

// 监听用户权限变化
watch(() => userAuthStore.permissions, () => {
  menuStore.refreshMenuPermissions()
})

// 组件挂载时初始化
onMounted(async () => {
  await menuStore.initMenuData()
  setActiveMenuByRoute()
})
</script>

<style scoped>
.dynamic-menu {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.dynamic-menu.collapsed {
  width: 64px;
}

.menu-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.menu-title {
  flex: 1;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.collapse-btn {
  padding: 4px;
  color: #909399;
}

.collapse-btn:hover {
  color: #409eff;
}

.menu-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
}

.menu-list {
  border: none;
  background: transparent;
}

.menu-list :deep(.el-menu-item),
.menu-list :deep(.el-sub-menu__title) {
  height: 50px;
  line-height: 50px;
  padding: 0 16px;
  color: #606266;
  border-bottom: 1px solid #f5f5f5;
}

.menu-list :deep(.el-menu-item:hover),
.menu-list :deep(.el-sub-menu__title:hover) {
  background-color: #f5f7fa;
  color: #409eff;
}

.menu-list :deep(.el-menu-item.is-active) {
  background-color: #ecf5ff;
  color: #409eff;
  border-right: 3px solid #409eff;
}

.menu-list :deep(.el-menu-item.is-disabled),
.menu-list :deep(.el-sub-menu.is-disabled .el-sub-menu__title) {
  color: #c0c4cc;
  cursor: not-allowed;
}

.menu-icon {
  margin-right: 8px;
  font-size: 16px;
  width: 16px;
  height: 16px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.emoji-icon {
  font-size: 16px;
  line-height: 1;
}

.menu-label {
  font-size: 14px;
}

/* 折叠状态下的样式 */
.dynamic-menu.collapsed .menu-header {
  padding: 16px 8px;
  justify-content: center;
}

.dynamic-menu.collapsed .menu-title {
  display: none;
}

.dynamic-menu.collapsed .menu-list :deep(.el-menu-item),
.dynamic-menu.collapsed .menu-list :deep(.el-sub-menu__title) {
  padding: 0 8px;
}

.dynamic-menu.collapsed .menu-icon {
  margin-right: 0;
}

.dynamic-menu.collapsed .menu-label {
  display: none;
}

/* 加载状态 */
.menu-loading {
  padding: 20px;
}

/* 空状态 */
.menu-empty {
  padding: 40px 20px;
  text-align: center;
}

/* 子菜单样式 */
.menu-list :deep(.el-sub-menu .el-menu-item) {
  padding-left: 48px;
  background-color: #fafafa;
}

.menu-list :deep(.el-sub-menu .el-menu-item:hover) {
  background-color: #f0f9ff;
}

.menu-list :deep(.el-sub-menu .el-menu-item.is-active) {
  background-color: #e6f7ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dynamic-menu {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
  }
  
  .dynamic-menu.show {
    transform: translateX(0);
  }
  
  .dynamic-menu.collapsed {
    width: 100%;
    max-width: 280px;
  }
}

/* 滚动条样式 */
.menu-content::-webkit-scrollbar {
  width: 4px;
}

.menu-content::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.menu-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.menu-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style> 